package com.cs.framework.web.view.support;

import java.io.IOException;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cs.framework.core.context.Application;
import com.cs.framework.web.view.View;
import com.cs.framework.web.view.ViewData;
import com.cs.framework.web.view.ViewInfo;

/**
 * 请求转发视图
 * 
 * @author hedongzhou
 * 
 */
public class ForwardView implements View {

	private final Log logger = LogFactory.getLog(getClass());

	/**
	 * 初始化
	 * 
	 * @param application
	 *            应用上下文
	 */
	public void init(Application application) {
	}

	/**
	 * 渲染视图
	 * 
	 * @param request
	 * @param response
	 * @param viewInfo
	 * @return
	 */
	public ViewInfo render(HttpServletRequest request, HttpServletResponse response, ViewInfo viewInfo) {
		// 把数据添加到请求属性上面
		ViewData viewData = viewInfo.getViewData();
		Set<String> keySet = viewData.keySet();
		for (String key : keySet) {
			request.setAttribute(key, viewData.getAttribute(key));
		}

		RequestDispatcher rd = request.getRequestDispatcher(viewInfo.getViewPath());

		try {
			rd.forward(request, response);
		} catch (ServletException e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}

		return null;
	}

}
